import { Repository, Like } from 'typeorm';
import { AppDataSource } from '../../config/database';
import { Dictionary } from '../../entities/Dictionary';

export class DictionaryService {
  private dictionaryRepository: Repository<Dictionary>;

  constructor() {
    this.dictionaryRepository = AppDataSource.getRepository(Dictionary);
  }

  async findAll(query: any = {}): Promise<{ dictionaries: Dictionary[]; total: number }> {
    const { page = 1, pageSize = 10, ...whereQuery } = query;
    
    const [dictionaries, total] = await this.dictionaryRepository.findAndCount({
      where: whereQuery,
      order: { id: 'DESC' },
      skip: (page - 1) * pageSize,
      take: pageSize
    });

    return { dictionaries, total };
  }

  async findById(id: number): Promise<Dictionary | null> {
    return await this.dictionaryRepository.findOne({
      where: { id }
    });
  }

  async findByName(name: string): Promise<Dictionary | null> {
    return await this.dictionaryRepository.findOne({
      where: { name }
    });
  }

  async findByType(type: string): Promise<Dictionary[]> {
    return await this.dictionaryRepository.find({
      where: {
        type: Like(`%${type}%`),
        enable: true 
      },
      order: { id: 'ASC' }
    });
  }

  async create(dictionaryData: Partial<Dictionary>): Promise<Dictionary> {
    const existingDictionary = await this.dictionaryRepository.findOne({
      where: { 
        code: dictionaryData.code,
        type: dictionaryData.type
      }
    });

    if (existingDictionary) {
      throw { status: 400, message: '相同类型下的字典编码已存在' };
    }

    return await this.dictionaryRepository.save(dictionaryData);
  }

  async update(id: number, updateData: Partial<Dictionary>): Promise<Dictionary | null> {
    const dictionary = await this.findById(id);
    if (!dictionary) {
      return null;
    }

    await this.dictionaryRepository.update(id, updateData);
    return await this.findById(id);
  }

  async delete(id: number): Promise<boolean> {
    const result = await this.dictionaryRepository.delete(id);
    return result.affected ? result.affected > 0 : false;
  }

  async findUniqueTypes(): Promise<string[]> {
    const result = await this.dictionaryRepository
      .createQueryBuilder('dictionary')
      .select('DISTINCT type')
      .getRawMany();
      
    return result.map(item => item.type);
  }
}

export const dictionaryService = new DictionaryService(); 